"""
Stock indicators window
"""

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import types
import datetime as dt

import ui_w_stockindicators
from analysis import indicators as ii
import agent
import time
import system.navalasystem as na
from misc import misc
from system import tradezone
from analysis import stockind
from system import configs as con

try:
    _fromUtf8 = QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s


class StockIndicators(QMainWindow, ui_w_stockindicators.Ui_StockIndicators):
    def __init__(self, parent=None):
        super(StockIndicators, self).__init__(parent)
        self.setupUi(self)
        self.AddItems()
        self.UpdateDateTimeEdit()
        self.resize(1, 1) # As small as possible!

    @misc.CatchException
    def Calculate(self, i):
        ind = ii._aa[i]
        print "Will calculate shit for indicator ``%s``" % ind.name
        try:
            ind.SetRefDt(self.dateTimeEditCalc.dateTime().toPyDateTime())
            obj = stockind.ManyStocksProcessor()
            obj.indicator = ind
            obj.SetStocksets(con.fig.GetRaw("workStocksets"))
            obj.CalculateEverything()
        except Exception as E:
            QMessageBox.critical(self, "Failed to calculate", E.message)
            raise

    @misc.CatchException
    def Purge(self, i):
        ind = ii._aa[i]
        try:
            z = QMessageBox.question(self, 'Purge',
                "Are you sure you wish to delete all recorded information for indicator ``%s``?" % ind.name, 
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if z == QMessageBox.Yes:
                na.vala.db.td_Purge(ind)
        except Exception as E:
            QMessageBox.critical(self, "Sth went wrong", E.message)
            raise

    @misc.CatchException
    def CheckBox(self, i, flag):
        ii.flagsChecked[i] = flag

    def AddItems(self):
        a = ii._aa # List of indicator objects
#how to stick custom data in the thing, like a number or the object itself
        for (i, ind) in enumerate(a):
            code = """
self.checkbox{0} = QCheckBox("{1}", self.centralwidget)
def on_checkbox{0}_stateChanged(self, state):
    print "APARASSI NEH"
    self.CheckBox({0}, self.checkbox{0}.isChecked())
self.on_checkbox{0}_stateChanged = types.MethodType(on_checkbox{0}_stateChanged, self, 
                                                 self.__class__) # bound method
self.connect(self.checkbox{0}, SIGNAL("stateChanged(int)"), 
             self.on_checkbox{0}_stateChanged)
self.gridLayout.addWidget(self.checkbox{0}, {0}, 0, 1, 1)
self.pushButtonA{0} = QPushButton("Calculate", self.centralwidget)
self.gridLayout.addWidget(self.pushButtonA{0}, {0}, 1, 1, 1)
def on_pushButtonA{0}_clicked(self):
    self.Calculate({0})
self.on_pushButtonA{0}_clicked = types.MethodType(on_pushButtonA{0}_clicked, self, 
                                                 self.__class__) # bound method
self.connect(self.pushButtonA{0}, SIGNAL("clicked()"), 
             self.on_pushButtonA{0}_clicked)

self.pushButtonB{0} = QPushButton("Purge", self.centralwidget)
self.gridLayout.addWidget(self.pushButtonB{0}, {0}, 2, 1, 1)
def on_pushButtonB{0}_clicked(self):
    self.Purge({0})
self.on_pushButtonB{0}_clicked = types.MethodType(on_pushButtonB{0}_clicked, self, 
                                                 self.__class__) # bound method
self.connect(self.pushButtonB{0}, SIGNAL("clicked()"), 
             self.on_pushButtonB{0}_clicked)
""".format(i, ind.name)
            exec(code)

        #QMetaObject.connectSlotsByName(self)
    
#    @misc.CatchException
#    @pyqtSignature("bool")
#    def on_pushButtonStart_clicked(self, checked):
#        self.CreateCustomAgent()


    def UpdateDateTimeEdit(self):
        self.dateTimeEditCalc.setDateTime(misc.EndOfDay(dt.datetime.today()))
        self.dateTimeEditRead.setDateTime(ii.readRefDt)


    @pyqtSignature("QDateTime")
    def on_dateTimeEditRead_dateTimeChanged(self, datetime):
        ii.readRefDt = self.dateTimeEditRead.dateTime().toPyDateTime()
